﻿/*
 DotNetNuke - http://www.dotnetnuke.com
 Copyright (c) 2002-2010 by DotNetNuke Corp.

 Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
 documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
 the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
 to permit persons to whom the Software is furnished to do so, subject to the following conditions:

 The above copyright notice and this permission notice shall be included in all copies or substantial portions 
 of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
 TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
 THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
 CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
 DEALINGS IN THE SOFTWARE.

*/
using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.IO;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml;

using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Services.FileSystem;
using DotNetNuke.Services.Localization;
using DotNetNuke.UI.Modules;
using DotNetNuke.UI.UserControls;


namespace DotNetNuke.Modules.UserDefinedTable
{


  public partial class Token2Xsl : ModuleUserControlBase
  {



    public enum ErrorOutput
    {
      TokenTemplate,
      XslTranformation,
      Save
    }

    
    private UserDefinedTableController _udtController;
    private DataSet SchemaDataSet;




    public Token2Xsl()
    {
      //base.Load += new EventHandler(this.Page_Load);
    }




    protected override void OnInit(EventArgs e)
    {
      base.OnInit(e);
      //base.Load += new EventHandler(this.Page_Load);

      cmdBack.Click += new EventHandler(cmdBack_Click);
      cmdConfirmOverwriteFile.Click += new EventHandler(cmdConfirmOverwriteFile_Click);
      cmdDenyOverwriteFile.Click += new EventHandler(cmdDenyOverwriteFile_Click);
      cmdGenerateXslt.Click += new EventHandler(cmdGenerateXslt_Click);
      cmdRebuildContent.Click += new EventHandler(cmdRebuildContent_Click);
      cmdRebuildDetail.Click += new EventHandler(cmdRebuildDetail_Click);
      cmdSaveFile.Click += new EventHandler(cmdSaveFile_Click);
      chkShowDetailView.CheckedChanged += new EventHandler(chkShowDetailView_CheckedChanged);
      ddlListTemplateType.SelectedIndexChanged += new EventHandler(ddlListTemplateType_SelectedIndexChanged);

    }




    //protected void Page_Load(object sender, EventArgs evt)
    protected override void OnLoad(EventArgs evt)
    {
      base.OnLoad(evt);

      this.SchemaDataSet = this.UdtController.GetSchemaDataset();
      this.SetupClientScripts();

      if (!this.IsPostBack)
      {
        if ((Utilities.CStrN(this.Request.QueryString["fileid"], "").Length > 0) || (Utilities.CStrN(this.Request.QueryString["Edit"], "").ToLowerInvariant() == "current"))
          this.EditExistingScriptAndTemplates();
        
        else
        {
          this.ViewState[Definition.XSLFolderName] = Definition.XSLFolderName;
          if (this.IsTrackingEmailMode)
            this.txtTrackingEmailTemplate.Text = "<style type=\"text/css\">" + "\r\n" + ".normal, .normalBold {font-family: Verdana, Tahoma, Arial, Helvetica;font-size: 11px;font-weight: normal;}" + "\r\n" + ".normalBold{font-weight: bold;}" + "\r\n" + "</style>" + "\r\n" + XSLTemplatingUtilities.GenerateDetailViewTokenText(this.UdtController.GetSchemaDataset().Tables[DataSetTableName.Fields], false);
          
          else
          {
            this.txtListTemplate.Text = this.BuildContent(this.GetBasicElements());
            this.txtListTemplateDelimiter.Enabled = false;
            this.txtListTemplateDelimiter.BackColor = Color.LightGray;
            this.txtDetailTemplate.Text = XSLTemplatingUtilities.GenerateDetailViewTokenText(this.SchemaDataSet.Tables[DataSetTableName.Fields]);
          }
          this.txtFolderName.Text = Definition.XSLFolderName;
          this.txtFileName.MaxLength = 200 - (this.ModuleContext.PortalSettings.HomeDirectoryMapPath + "/" + Definition.XSLFolderName + "/").Length;
        }
        this.ListTemplateSetHeaderAndFooter();
        this.TemplatesPopulateColumnDropDownLists();
        this.TemplatesSetVisibility(!this.IsTrackingEmailMode);
      }
    }




    private string BuildContent(IList Elements)
    {
      string selectedValue = this.ddlListTemplateType.SelectedValue;

      if (Elements == null)
        return string.Empty;
      
      this.CurrentListType = selectedValue;
      using (StringWriter writer = new StringWriter())
      {
        string delimiter = this.GetDelimiter(true);
        using (XmlTextWriter writer2 = new XmlTextWriter(writer))
        {
          bool flag = false;
          writer2.Formatting = Formatting.Indented;

          if ( !string.IsNullOrEmpty(this.GetOuterTag(this.ddlListTemplateType.SelectedValue)) )
          {
            writer2.WriteStartElement(this.GetOuterTag(this.ddlListTemplateType.SelectedValue));
            writer2.WriteAttributeString("class", "Normal");
          }

          foreach(string data in Elements)
          {
            if ( !string.IsNullOrEmpty(this.GetInnerTag()) )
              writer2.WriteStartElement(this.GetInnerTag());
            
            if (flag)
              writer2.WriteRaw(delimiter);
            
            else
              flag = true;
            
            writer2.WriteRaw(data);
            if ( !string.IsNullOrEmpty(this.GetInnerTag()) )
              writer2.WriteEndElement();
            
          }

          if ( !string.IsNullOrEmpty(this.GetOuterTag(this.ddlListTemplateType.SelectedValue)) )
            writer2.WriteEndElement();
          
          writer2.Flush();
        }
        return writer.ToString();
      }
    }




    private void cmdBack_Click(object sender, EventArgs evt)
    {
      this.Response.Redirect(this.ReturnUrl, true);
    }




    private void cmdColumnsHelp_Click(object sender, EventArgs evt)
    {
      string str2 = this.ResolveUrl("HelpPopup.aspx?resourcekey=Help_HiddenColumns");
      string script = "<script language='text/javascript'>   window.open('" + str2 + "', '',                'width=800, height=400, location=no, menubar=no, resizable=yes, scrollbars=yes, status=no, toolbar=no')</script>";
      this.Page.ClientScript.RegisterStartupScript(this.GetType(), "columnsHelpPopup", script);
    }




    private void cmdConfirmOverwriteFile_Click(object sender, EventArgs evt)
    {
      string fileContent = this.GetFileContent();
      string fileName = this.GetFileName();
      FolderInfo folder = this.GetFolder();
      this.SaveScript(fileContent, fileName, folder, true);
      this.UpdateSettings(folder.FolderPath + fileName);
      this.Response.Redirect(this.ReturnUrl, true);
    }




    private void cmdDenyOverwriteFile_Click(object sender, EventArgs evt)
    {
      this.txtFileName.Text = "";
      this.LockControls(false);
      this.panConfirm.Visible = false;
    }




    private void cmdGenerateXslt_Click(object sender, EventArgs evt)
    {
      this.lblTemplateError.Visible = false;
      this.lblXslScriptError.Visible = false;
      this.lblSaveXslError.Visible = false;
      string text = this.txtListTemplate.Text;
      string x = this.txtDetailTemplate.Text;
      string headerView = this.txtHeaderTemplate.Text;
      if (this.IsTrackingEmailMode)
      {
        if (this.isValid(this.txtTrackingEmailTemplate.Text, ErrorOutput.XslTranformation, true))
        {
          this.txtXslScript.Text = XSLTemplatingUtilities.TransformTokenTextToXslScript(this.UdtController.GetSchemaDataset(), this.txtTrackingEmailTemplate.Text);
          this.txtXslScript.Enabled = true;
          this.ShowXslEditor();
        }
      }
      else if (this.isValid(text, ErrorOutput.XslTranformation, true) && (!this.chkShowDetailView.Checked || this.isValid(x, ErrorOutput.XslTranformation, true)))
      {
        this.txtXslScript.Text = XSLTemplatingUtilities.TransformTokenTextToXslScript(this.SchemaDataSet, text, x, headerView, this.chkEnablePaging.Checked, this.chkEnableSorting.Checked, this.chkEnableSearch.Checked, this.chkShowDetailView.Checked, this.CurrentListType);
        this.txtXslScript.Enabled = true;
        this.ShowXslEditor();
      }
    }




    private void cmdRebuildContent_Click(object sender, EventArgs evt)
    {
      this.ddlListTemplateType.Enabled = true;
      this.lblTemplateError.Visible = false;
      this.lblXslScriptError.Visible = false;
      this.lblSaveXslError.Visible = false;
      this.txtListTemplate.Text = this.BuildContent(this.GetBasicElements());
      if (this.chkShowDetailView.Checked & (this.txtListTemplate.Text.IndexOf("UDT:DetailView") < 0))
      {
        this.txtListTemplate.Text = this.txtListTemplate.Text.Replace("UDT:EditLink", "UDT:DetailView");
      }
      this.txtXslScript.Text = "";
      this.txtFileName.BackColor = Color.LightGray;
      this.txtFileName.Enabled = false;
      this.cmdSaveFile.Enabled = false;
    }




    private void cmdRebuildDetail_Click(object sender, EventArgs evt)
    {
      this.txtDetailTemplate.Text = XSLTemplatingUtilities.GenerateDetailViewTokenText(this.SchemaDataSet.Tables[DataSetTableName.Fields]);
    }




    protected void cmdRebuildTrackingEmail_Click(object sender, EventArgs evt)
    {
      this.txtTrackingEmailTemplate.Text = "<style type=\"text/css\">" + "\r\n" + ".normal, .normalBold {font-family: Verdana, Tahoma, Arial, Helvetica;font-size: 11px;font-weight: normal;}" + "\r\n" + ".normalBold{font-weight: bold;}" + "\r\n" + "</style>" + "\r\n" + XSLTemplatingUtilities.GenerateDetailViewTokenText(this.UdtController.GetSchemaDataset().Tables[DataSetTableName.Fields], false);
    }

    private void cmdSaveFile_Click(object sender, EventArgs evt)
    {
      if (this.isValid(this.txtXslScript.Text, ErrorOutput.Save, false))
      {
        string fileContent = this.GetFileContent();
        string fileName = this.GetFileName();
        if (fileName.Length > 4)
        {
          FolderInfo folder = this.GetFolder();
          if (this.SaveScript(fileContent, fileName, folder, false))
          {
            this.UpdateSettings(folder.FolderPath + fileName);
            this.Response.Redirect(this.ReturnUrl, true);
          }
          else
          {
            this.LockControls(true);
            this.panConfirm.Visible = true;
          }
        }
      }
    }




    private void ddlListTemplateType_SelectedIndexChanged(object sender, EventArgs evt)
    {
      this.lblTemplateError.Visible = false;
      this.lblXslScriptError.Visible = false;
      this.lblSaveXslError.Visible = false;
      if (this.isValid(this.txtListTemplate.Text, ErrorOutput.TokenTemplate, true))
      {
        if (this.GetCurrentElements() != null)
        {
          this.txtListTemplate.Text = this.BuildContent(this.GetCurrentElements());
          this.setupDelimiter();
        }
        else
        {
          this.ddlListTemplateType.SelectedValue = this.CurrentListType;
          this.lblTemplateError.Text = DotNetNuke.Services.Localization.Localization.GetString("noTransformButValid", this.LocalResourceFile);
          this.lblTemplateError.Visible = true;
        }
      }
      else
      {
        this.ddlListTemplateType.SelectedValue = this.CurrentListType;
      }
      this.ListTemplateSetHeaderAndFooter();
      this.txtXslScript.Text = "";
      this.txtFileName.BackColor = Color.LightGray;
      this.txtFileName.Enabled = false;
      this.cmdSaveFile.Enabled = false;
    }




    private void EditExistingScriptAndTemplates()
    {
      try
      {
        int num;
        FileController controller = new FileController();
        if (Utilities.CStrN(this.Request.QueryString["Edit"], "").ToLowerInvariant() == "current")
        {
          num = controller.ConvertFilePathToFileId((string)this.ModuleContext.Settings[SettingName.XslUserDefinedStyleSheet], this.ModuleContext.PortalId);
          this.ReturnUrl = Globals.NavigateURL();
        }
        else
        {
          num = int.Parse(this.Request.QueryString["fileid"]);
          this.ReturnUrl = this.ModuleContext.EditUrl("Manage");
        }
        DotNetNuke.Services.FileSystem.FileInfo fileById = controller.GetFileById(num, this.ModuleContext.PortalId);
        if (fileById.Extension.ToLowerInvariant().StartsWith("xsl") && Utilities.hasWritePermission(fileById.Folder, this.ModuleContext.PortalId))
        {
          string str;
          this.ViewState[Definition.XSLFolderName] = fileById.Folder;
          this.txtFolderName.Text = fileById.Folder;
          this.txtFileName.Text = fileById.FileName;
          this.txtFileName.MaxLength = 200 - (this.ModuleContext.PortalSettings.HomeDirectoryMapPath + "/" + fileById.Folder).Length;
          using (Stream stream = FileSystemUtils.GetFileStream(fileById))
          {
            using (StreamReader reader = new StreamReader(stream))
            {
              str = reader.ReadToEnd();
            }
          }
          str = str.Replace("&#160;", "{5A255853-D9A0-4f46-9E9D-F661DC4874CD}");
          XmlDocument doc = new XmlDocument();
          doc.LoadXml(str);
          XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
          nsmgr.AddNamespace("udt", "DotNetNuke/UserDefinedTable");
          nsmgr.AddNamespace("xsl", "http://www.w3.org/1999/XSL/Transform");
          XmlNode node = doc.SelectSingleNode("/xsl:stylesheet", nsmgr);
          XmlElement oldChild = (XmlElement)node.SelectSingleNode("udt:template", nsmgr);
          if (oldChild != null)
          {
            if (oldChild.HasAttribute("headerView"))
            {
              this.txtHeaderTemplate.Text = HttpUtility.HtmlDecode(oldChild.Attributes["headerView"].Value).Replace("{5A255853-D9A0-4f46-9E9D-F661DC4874CD}", "&#160;");
            }
            if (oldChild.HasAttribute("listView"))
            {
              this.txtListTemplate.Text = HttpUtility.HtmlDecode(oldChild.Attributes["listView"].Value).Replace("{5A255853-D9A0-4f46-9E9D-F661DC4874CD}", "&#160;");
            }
            if (oldChild.HasAttribute("detailView"))
            {
              this.txtDetailTemplate.Text = HttpUtility.HtmlDecode(oldChild.Attributes["detailView"].Value).Replace("{5A255853-D9A0-4f46-9E9D-F661DC4874CD}", "&#160;");
            }
            this.chkEnablePaging.Checked = oldChild.HasAttribute("paging");
            this.chkEnableSorting.Checked = oldChild.HasAttribute("sorting");
            this.chkEnableSearch.Checked = oldChild.HasAttribute("searching");
            this.chkShowDetailView.Checked = oldChild.HasAttribute("showDetailView");
            if (oldChild.HasAttribute("isTrackingMode"))
            {
              this.IsTrackingEmailMode = true;
              this.txtTrackingEmailTemplate.Text = HttpUtility.HtmlDecode(oldChild.Attributes["trackingEmail"].Value).Replace("{5A255853-D9A0-4f46-9E9D-F661DC4874CD}", "&#160;");
            }
            if (oldChild.HasAttribute("listType"))
            {
              this.ddlListTemplateType.SelectedValue = oldChild.Attributes["listType"].Value;
              this.setupDelimiter();
            }
            if (oldChild.HasAttribute("delimiter"))
            {
              this.txtListTemplateDelimiter.Text = HttpUtility.HtmlDecode(oldChild.Attributes["delimiter"].Value);
            }
            node.RemoveChild(oldChild);
          }
          this.txtXslScript.Text = XSLTemplatingUtilities.PrettyPrint(doc).Replace("{5A255853-D9A0-4f46-9E9D-F661DC4874CD}", "&#160;");
          this.ShowXslEditor();
        }
      }
      catch (Exception e)
      {

        Exception exception = e;

      }
    }

    private IList GetBasicElements()
    {
      ArrayList list = new ArrayList();
      list.Add("[UDT:EditLink]");

      foreach(DataRow current in this.SchemaDataSet.Tables[DataSetTableName.Fields].Rows)
      {
        if (Convert.ToBoolean(current[FieldsTableColumn.Visible]))
          list.Add(string.Format("[{0}]", XmlConvert.DecodeName((string)current[FieldsTableColumn.ValueColumn])));
        
      }
      return list;
    }





    private IList GetCurrentElements()
    {
      IList list;
      string text = this.txtListTemplate.Text;
      try
      {
        if (this.CurrentListType == "table")
        {
          XmlDocument document = new XmlDocument();
          document.LoadXml(text);
          ArrayList list2 = new ArrayList();
          foreach(XmlElement current in document.SelectNodes("/tr/td"))
            list2.Add(current.InnerXml);
          
          return list2;
        }

        if (this.CurrentListType != "nothing")
        {
          XmlDocument document2 = new XmlDocument();
          document2.LoadXml(text);
          XmlNode node = document2.SelectSingleNode(string.Format("/{0}", this.GetOuterTag(this.CurrentListType)));
          if (node != null)
            text = node.InnerXml;
          
        }
        list = Regex.Split(text, this.GetDelimiter(false));
      }
      catch (Exception e)
      {
        Exception exception = e;
        list = null;
      }
      return list;
    }




    private string GetDelimiter(bool notCurrent = true)
    {
      if (notCurrent && (this.ddlListTemplateType.SelectedValue == "table"))
      {
        return "";
      }
      string text = "";
      if (this.txtListTemplateDelimiter.Text != "")
      {
        text = this.txtListTemplateDelimiter.Text;
      }
      return (text + "\r\n");
    }

    private string GetFileContent()
    {
      return this.txtXslScript.Text.Replace("</xsl:stylesheet>", this.TokenTemplateSettingsAsXml() + "\r\n</xsl:stylesheet>");
    }

    private string GetFileName()
    {
      string str = Globals.CleanFileName(this.txtFileName.Text.Trim());
      if (!str.ToLowerInvariant().EndsWith(".xsl"))
      {
        str = str + ".xsl";
      }
      this.txtFileName.Text = str;
      return str;
    }

    private FolderInfo GetFolder()
    {
      return Utilities.GetFolder(this.ModuleContext.PortalSettings, Utilities.CStrN((this.ViewState[Definition.XSLFolderName]), ""), Definition.XSLFolderName);
    }

    private string GetInnerTag()
    {
      if (this.ddlListTemplateType.SelectedValue == "table")
      {
        return "td";
      }
      return "";
    }

    private string GetOuterTag(string listType)
    {
      string str2 = listType;
      switch (str2)
      {
        case "table":
          return "tr";

        case "nothing":
          return "";
      }
      if ((str2 != "ol") && (str2 != "ul"))
      {
        return listType;
      }
      return "li";
    }

    private void chkShowDetailView_CheckedChanged(object sender, EventArgs evt)
    {
      this.TemplatesSetVisibility(true);
      this.TemplatesPopulateColumnDropDownLists();
      this.dshDetailView.IsExpanded = this.chkShowDetailView.Checked;
    }

    private bool isValid(string x, ErrorOutput pos, bool addRoot)
    {
      bool flag;
      if (addRoot)
      {
        x = string.Format("<root>{0}</root>", x);
      }
      XmlTextReader reader = new XmlTextReader(new StringReader(x));
      try
      {
        while (reader.Read())
        {
        }
        flag = true;
      }
      catch (Exception e)
      {

        Exception exception = e;
        switch (pos)
        {
          case ErrorOutput.TokenTemplate:
            this.lblTemplateError.Text = DotNetNuke.Services.Localization.Localization.GetString("error.Text", this.LocalResourceFile) + exception.Message;
            this.lblTemplateError.Visible = true;
            break;

          case ErrorOutput.XslTranformation:
            this.lblXslScriptError.Text = DotNetNuke.Services.Localization.Localization.GetString("error.Text", this.LocalResourceFile) + exception.Message;
            this.lblXslScriptError.Visible = true;
            break;

          case ErrorOutput.Save:
            this.lblSaveXslError.Text = DotNetNuke.Services.Localization.Localization.GetString("error.Text", this.LocalResourceFile) + exception.Message;
            this.lblSaveXslError.Visible = true;
            break;
        }
        flag = false;

      }
      finally
      {
        if (reader != null)
        {
          ((IDisposable)reader).Dispose();
        }
      }
      return flag;
    }

    private void ListTemplateSetHeaderAndFooter()
    {
      switch (this.ddlListTemplateType.SelectedValue)
      {
        case "table":
          this.lblListTemplateHead.Text = "&lt;table&gt;";
          this.lblListTemplateFooter.Text = "...<br/>&lt;/table&gt;";
          break;

        case "div":
          this.lblListTemplateHead.Text = "";
          this.lblListTemplateFooter.Text = "...";
          break;

        case "ol":
          this.lblListTemplateHead.Text = "&lt;ol&gt;";
          this.lblListTemplateFooter.Text = "...<br/>&lt;/ol&gt;";
          break;

        case "ul":
          this.lblListTemplateHead.Text = "&lt;ul&gt;";
          this.lblListTemplateFooter.Text = "...<br/>&lt;/ul&gt;";
          break;

        case "p":
          this.lblListTemplateHead.Text = "";
          this.lblListTemplateFooter.Text = "...";
          break;

        case "nothing":
          this.lblListTemplateHead.Text = "...";
          this.lblListTemplateFooter.Text = "";
          break;
      }
    }

    private void LockControls(bool IsLockRequested)
    {
      if (IsLockRequested)
      {
        this.cmdRebuildContent.Enabled = false;
        this.cmdSaveFile.Enabled = false;
        this.cmdGenerateXslt.Enabled = false;
        this.addColumnToListTemplate.Enabled = false;
        this.addColumnWithTagsToListTemplate.Enabled = false;
        this.ddlListTemplateType.Enabled = false;
        this.ddlColumnsForListView.Enabled = false;
        this.txtListTemplate.Enabled = false;
        this.txtFileName.Enabled = false;
        this.txtXslScript.Enabled = false;
      }
      else
      {
        this.cmdRebuildContent.Enabled = true;
        this.cmdSaveFile.Enabled = true;
        this.cmdGenerateXslt.Enabled = true;
        this.addColumnToListTemplate.Enabled = true;
        this.addColumnWithTagsToListTemplate.Enabled = true;
        this.ddlListTemplateType.Enabled = true;
        this.ddlColumnsForListView.Enabled = true;
        this.txtListTemplate.Enabled = true;
        this.txtFileName.Enabled = true;
        this.txtXslScript.Enabled = true;
      }
    }

    


    private bool SaveScript(string fileContent, string fileName, FolderInfo folder, bool ForceOverWrite)
    {
      return Utilities.SaveScript(this.ModuleContext.PortalId, fileContent, fileName, folder, ForceOverWrite);
    }

    private void SetupClientScripts()
    {
      this.cmdRebuildContent.Attributes.Add("onclick", string.Format("return confirm('{0}')", DotNetNuke.Services.Localization.Localization.GetString("confirmOnRebuild.Text", this.LocalResourceFile)));
      this.addColumnToListTemplate.Attributes.Add("onclick", string.Format("AddCurrentItemIntoTextBox(event, '{0}', '{1}', '{2}', 'False')", this.txtListTemplate.ClientID, this.ddlColumnsForListView.ClientID, this.txtXslScript.ClientID));
      this.addColumnWithTagsToListTemplate.Attributes.Add("onclick", string.Format("AddCurrentItemIntoTextBox(event, '{0}', '{1}', '{2}', 'True')", this.txtListTemplate.ClientID, this.ddlColumnsForListView.ClientID, this.txtXslScript.ClientID));
      this.addColumnToDetailTemplate.Attributes.Add("onclick", string.Format("AddCurrentItemIntoTextBox(event, '{0}', '{1}', '{2}', 'False')", this.txtDetailTemplate.ClientID, this.ddlColumnsForDetailView.ClientID, this.txtXslScript.ClientID));
      this.addColumnToTrackingEmail.Attributes.Add("onclick", string.Format("AddCurrentItemIntoTextBox(event, '{0}', '{1}', '{2}', 'False')", this.txtTrackingEmailTemplate.ClientID, this.ddlColumnsForTrackingEmail.ClientID, this.txtXslScript.ClientID));
      this.addHeader.Attributes.Add("onclick", string.Format("AddCurrentItemIntoTextBox(event, '{0}', '{1}', '{2}', 'False')", this.txtHeaderTemplate.ClientID, this.ddlHeaders.ClientID, this.txtXslScript.ClientID));
      string str = this.ResolveUrl("HelpPopup.aspx?resourcekey=Help_HiddenColumns");
      this.hlpColumns.NavigateUrl = string.Format("javascript:OpenHelpWindow('{0}');", str);
    }

    private void setupDelimiter()
    {
      if (this.ddlListTemplateType.SelectedValue == "table")
      {
        this.txtListTemplateDelimiter.Enabled = false;
        this.txtListTemplateDelimiter.BackColor = Color.LightGray;
        this.addColumnWithTagsToListTemplate.Enabled = true;
      }
      else
      {
        this.txtListTemplateDelimiter.Enabled = true;
        this.txtListTemplateDelimiter.BackColor = Color.White;
        this.addColumnWithTagsToListTemplate.Enabled = false;
      }
    }

    private void ShowXslEditor()
    {
      this.txtFileName.BackColor = Color.White;
      this.txtFileName.Enabled = true;
      this.cmdSaveFile.Enabled = true;
      this.dshHtml.IsExpanded = false;
      this.dshXslt.IsExpanded = true;
      this.dshSave.IsExpanded = true;
      this.dshDetailView.IsExpanded = false;
      this.dshOptions.IsExpanded = false;
      this.dshListView.IsExpanded = false;
    }

    private void TemplatesPopulateColumnDropDownLists()
    {
      this.ddlColumnsForListView.Items.Clear();
      this.ddlColumnsForDetailView.Items.Clear();
      this.ddlColumnsForTrackingEmail.Items.Clear();
      this.ddlColumnsForListView.Items.Add(new ListItem("UDT:EditLink", "[UDT:EditLink]"));
      this.ddlColumnsForTrackingEmail.Items.Add(new ListItem("UDT:EditLink", "[UDT:EditLink]"));

      if (this.chkShowDetailView.Checked)
        this.ddlColumnsForListView.Items.Add(new ListItem("UDT:DetailView", "[UDT:DetailView]"));

      this.ddlColumnsForDetailView.Items.Add(new ListItem("UDT:EditLink", "[UDT:EditLink]"));
      this.ddlColumnsForDetailView.Items.Add(new ListItem("UDT:ListView", "[UDT:ListView]"));

      string columnName;

      foreach(DataColumn current in this.SchemaDataSet.Tables[DataSetTableName.Data].Columns)
      {
        columnName = current.ColumnName;
        if (current.ColumnName != "EditLink")
        {
          this.ddlColumnsForListView.Items.Add(new ListItem(columnName, string.Format("[{0}]", columnName)));
          this.ddlColumnsForDetailView.Items.Add(new ListItem(columnName, string.Format("[{0}]", columnName)));
          this.ddlColumnsForTrackingEmail.Items.Add(new ListItem(columnName, string.Format("[{0}]", columnName)));
        }
      }
      
      this.ddlColumnsForListView.Items.Add(new ListItem("[ ] Hard Space", "[ ]"));
      this.ddlColumnsForDetailView.Items.Add(new ListItem("[ ] Hard Space", "[ ]"));
      this.ddlColumnsForTrackingEmail.Items.Add(new ListItem("[ ] Hard Space", "[ ]"));

      foreach (string str2 in Enum.GetNames(typeof(XSLTemplatingUtilities.ContextValues)))
      {
        this.ddlColumnsForListView.Items.Add(new ListItem(string.Format("Context:{0}", str2), string.Format("[Context:{0}]", str2)));
        this.ddlColumnsForDetailView.Items.Add(new ListItem(string.Format("Context:{0}", str2), string.Format("[Context:{0}]", str2)));
        this.ddlColumnsForTrackingEmail.Items.Add(new ListItem(string.Format("Context:{0}", str2), string.Format("[Context:{0}]", str2)));
      }
      this.ddlHeaders.Items.Clear();
      string text;

      foreach(DataRow row in this.SchemaDataSet.Tables[DataSetTableName.Fields].Rows)
      {
        text = (string)row[FieldsTableColumn.Title];
        this.ddlHeaders.Items.Add(new ListItem(text, string.Format("[{0}]", text)));
      }
    }




    private void TemplatesSetVisibility(bool IsViewMode)
    {
      if (IsViewMode)
      {
        this.dshListView.Visible = true;
        this.dshOptions.Visible = true;
        this.dshTrackingEmail.Visible = false;
        this.dvListview.Visible = true;
        this.dvOptions.Visible = true;
        this.dvTrackingEmail.Visible = false;
        bool flag = this.chkShowDetailView.Checked;
        this.dshDetailView.Visible = flag;
        this.dvDetailView.Visible = flag;
        if (flag & (this.txtListTemplate.Text.IndexOf("UDT:DetailView") < 0))
        {
          this.txtListTemplate.Text = this.txtListTemplate.Text.Replace("UDT:EditLink", "UDT:DetailView");
        }
        if (!flag)
        {
          if (this.txtListTemplate.Text.IndexOf("UDT:EditLink") > 0)
          {
            this.txtListTemplate.Text = this.txtListTemplate.Text.Replace("UDT:DetailView", "");
          }
          else
          {
            this.txtListTemplate.Text = this.txtListTemplate.Text.Replace("UDT:DetailView", "UDT:EditLink");
          }
        }
      }
      else
      {
        this.dshListView.Visible = false;
        this.dshOptions.Visible = false;
        this.dshDetailView.Visible = false;
        this.dshTrackingEmail.Visible = true;
        this.dvListview.Visible = false;
        this.dvOptions.Visible = false;
        this.dvDetailView.Visible = false;
        this.dvTrackingEmail.Visible = true;
      }
    }





    private string TokenTemplateSettingsAsXml()
    {
      using (StringWriter writer = new StringWriter())
      {
        using (XmlTextWriter writer2 = new XmlTextWriter(writer))
        {
          writer2.WriteStartElement("udt:template");
          writer2.WriteAttributeString("listType", this.ddlListTemplateType.SelectedValue);
          writer2.WriteAttributeString("delimiter", this.txtListTemplateDelimiter.Text);
          writer2.WriteAttributeString("listView", this.txtListTemplate.Text);
          writer2.WriteAttributeString("headerView", this.txtHeaderTemplate.Text);
          writer2.WriteAttributeString("detailView", this.txtDetailTemplate.Text);
          writer2.WriteAttributeString("trackingEmail", this.txtTrackingEmailTemplate.Text);
          if (this.chkEnablePaging.Checked)
          {
            writer2.WriteAttributeString("paging", "true");
          }
          if (this.chkEnableSearch.Checked)
          {
            writer2.WriteAttributeString("searching", "true");
          }
          if (this.chkEnableSorting.Checked)
          {
            writer2.WriteAttributeString("sorting", "true");
          }
          if (this.chkShowDetailView.Checked)
          {
            writer2.WriteAttributeString("showDetailView", "true");
          }
          if (this.IsTrackingEmailMode)
          {
            writer2.WriteAttributeString("isTrackingMode", "true");
          }
          writer2.WriteEndElement();
        }
        return writer.ToString();
      }
    }





    private void UpdateSettings(string FileWithPath)
    {
      ModuleController controller = new ModuleController();
      if (this.IsTrackingEmailMode)
      {
        controller.UpdateTabModuleSetting(this.ModuleContext.TabModuleId, SettingName.TrackingScript, FileWithPath);
      }
      else
      {
        controller.UpdateTabModuleSetting(this.ModuleContext.TabModuleId, SettingName.RenderingMethod, RenderingMethod.UserdefinedXSL);
        controller.UpdateTabModuleSetting(this.ModuleContext.TabModuleId, SettingName.XslUserDefinedStyleSheet, FileWithPath);
      }
      controller = null;
    }





    private string CurrentListType
    {
      get
      {
        return Utilities.CStrN((this.ViewState["CurrentListType"]), this.ddlListTemplateType.SelectedValue);
      }
      set
      {
        this.ViewState["CurrentListType"] = value;
      }
    }





    private bool IsTrackingEmailMode
    {
      get
      {
        return Utilities.CBoolN((this.ViewState["tracking"]), Utilities.CStrN(this.Request.QueryString["tracking"], "").Length > 0);
      }
      set
      {
        this.ViewState["tracking"] = value;
      }
    }





    private string ReturnUrl
    {
      get
      {
        return Utilities.CStrN((this.ViewState["ReturnUrl"]), this.ModuleContext.EditUrl("Manage"));
      }
      set
      {
        this.ViewState["ReturnUrl"] = value;
      }
    }




    private UserDefinedTableController UdtController
    {
      get
      {
        if (this._udtController == null)
        {
          this._udtController = new UserDefinedTableController(this.ModuleContext);
        }
        return this._udtController;
      }
    }




  }

}

